package com.atguigu.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @version 1.0
 * @Author 马冰
 * @Date 2024/12/18 13:57
 * @注释
 */
@Component
@Aspect
public class LoggerAspect {

    @Pointcut("execution(* com.atguigu.aop.*.*(..))")
    public void PointCut(){}

    //@Before("execution(public int com.atguigu.aop.CalcImpl.add(int,int))")
    @Before("PointCut()")
    public void beforeMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("前置通知, 方法名:" + name + ", 参数: " + Arrays.toString(args));
    }

    @After("PointCut()")
    public void AfterMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("后置通知, 方法名:" + name + ", 执行结束");
    }

    @AfterReturning(value = "PointCut()",returning = "result")
    public void AfterReturningMethod(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("返回通知, 方法名: " + name + ", 结果: " + result);
    }

    @AfterThrowing(value = "PointCut()",throwing = "e")
    public void AfterThrowingMethod(JoinPoint joinPoint, Exception e) {
        String name = joinPoint.getSignature().getName();
        System.out.println("异常通知, 方法名: " + name + ", 异常: " + e);
    }


    //环绕通知
    @Around("PointCut()")
    public Object AroundMethod(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            System.out.println("环绕通知(前置)");
            //调用目标对象的方法
            result = joinPoint.proceed();
            System.out.println("环绕通知(返回)");
        } catch (Throwable e) {
            System.out.println("环绕通知(异常)");
            throw new RuntimeException(e);
        } finally {
            System.out.println("环绕通知(后置)");
        }
        return result;
    }
}
